package com.asiainfo.dacp.datastash.broker.schedule;

import com.asiainfo.dacp.datastash.broker.schedule.buildinjob.StashTraceLogCrtTableJob;
import com.asiainfo.dacp.datastash.broker.schedule.buildinjob.StashUnitInitJob;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogVo;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogger;
import org.quartz.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 调度的服务，自管理类，自行实现调度的能力
 *
 * @author MeiKefu
 * @date 2017-10-31
 */
@Service
public class StashSchedulerInternal implements StashScheduler {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private StashTraceLogger tracelog;
    private String clzName = this.getClass().getSimpleName();

    public void init(){
        /**
         * 1.初始化内部定时任务
         */
        String groupName = "datastash_buildin";


        {
            String jobName = StashUnitInitJob.class.getName();
            JobDetail jobDetail = JobBuilder.newJob(StashUnitInitJob.class).withDescription("StashUnitInitJob").withIdentity(jobName, groupName).build();
            
            //fix: 15分钟的间隔明显不能及时加载库中新增job 后续考虑选主完成后该broker以近实时去获取新增或修改任务，其他broker等待就行了
            //CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/15 * * * ?");
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 * * * * ?");
            
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName).withSchedule(scheduleBuilder).build();

            try {
                scheduler.scheduleJob(jobDetail, trigger);
                scheduler.triggerJob(jobDetail.getKey());
                tracelog.info(new StashTraceLogVo(clzName,"internalschedule:init:complete","启动StashUnitInitJob"));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }

        /**
         * 2.初始化新建轨迹表分区任务
         * 每6个小时执行一次
         */
        {
            String jobName = StashTraceLogCrtTableJob.class.getName();
            JobDetail jobDetail = JobBuilder.newJob(StashTraceLogCrtTableJob.class).withDescription("StashTraceLogCrtTableJob").withIdentity(jobName, groupName).build();
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 0/4 * * ?");
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName).withSchedule(scheduleBuilder).build();

            try {
                scheduler.scheduleJob(jobDetail, trigger);
                tracelog.info(new StashTraceLogVo(clzName,"internalschedule:init:complete","启动StashTraceLogCrtTableJob"));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }

    }
}
